package com.small.nacos.naming.core;


import com.alibaba.nacos.common.utils.CollectionUtils;
import com.small.nacos.naming.healthcheck.ClientBeatCheckTask;
import com.small.nacos.naming.healthcheck.HealthCheckReactor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author zhoujin
 * @Date 2022/7/23 11:32
 */
public class Service extends com.alibaba.nacos.api.naming.pojo.Service{

    private String namespaceId;

    private volatile long lastModifiedMillis = 0L;

    private ClientBeatCheckTask clientBeatCheckTask = new ClientBeatCheckTask(this);

    private Map<String, Cluster> clusterMap = new HashMap();


    public List<Instance> srvIPs(List<String> clusters) {
        if (CollectionUtils.isEmpty(clusters)) {
            clusters = new ArrayList<>();
            clusters.addAll(clusterMap.keySet());
        }
        return allIPs(clusters);
    }

    public List<Instance> allIPs(List<String> clusters) {
        List<Instance> result = new ArrayList<>();
        for (String cluster : clusters) {
            Cluster clusterObj = clusterMap.get(cluster);
            if (clusterObj == null) {
                continue;
            }

            result.addAll(clusterObj.allIPs());
        }
        return result;
    }


    public Map<String, Cluster> getClusterMap() {
        return clusterMap;
    }

    public void init(){
        HealthCheckReactor.scheduleCheck(clientBeatCheckTask);
    }

    public void destroy() throws Exception {
        HealthCheckReactor.cancelCheck(clientBeatCheckTask);
    }

    public String getNamespaceId() {
        return namespaceId;
    }

    public void setNamespaceId(String namespaceId) {
        this.namespaceId = namespaceId;
    }

    public long getLastModifiedMillis() {
        return lastModifiedMillis;
    }

    public void setLastModifiedMillis(long lastModifiedMillis) {
        this.lastModifiedMillis = lastModifiedMillis;
    }
}
